/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.query;

import java.util.Map;

import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.Clazz;
import com.koylu.caffein.query.target.Target;

public class OracleQuery extends Query {
	
	public OracleQuery(CaffeinConfig caffeinConfig, Clazz clazz, String alias) {
		super(caffeinConfig, clazz, alias);
	}
	
	public StringBuffer listQuery(CaffeinConfig caffeinConfig, Map<String, Clazz> aliasMap, Target target, int firstResult, int maxResult) throws Exception{
		/*
	       	SELECT * FROM (
  				SELECT rownumbered_table.*, rownum-1 rnum FROM (
    				SELECT xxx.id,xxx.name FROM test_role xxx ORDER BY xxx.name ASC
  				) rownumbered_table WHERE rownum <= 6
			) WHERE rnum >= 4
		*/
		StringBuffer query = new StringBuffer("SELECT * FROM (");
		query.append("SELECT rownumbered_table.*, (rownum-1) rnum FROM (");
		query.append("SELECT ").append(target.toQuery(caffeinConfig, aliasMap)).append(fromTables()).append(whereClause()).append(groupBy()).append(orderBy());
		query.append(") rownumbered_table WHERE rownum <= ").append(firstResult + maxResult);
		query.append(") WHERE rnum >= ").append(firstResult);
		return query;
	}
}